from flask import Flask
from config import app_state
from routes import bp
from scheduler import init_scheduler, shutdown_scheduler
import logging
import sys
import os
import secrets

app = Flask(__name__)
# 配置 Flask Session
app.secret_key = os.environ.get('SECRET_KEY', secrets.token_hex(16))
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SESSION_PERMANENT'] = False
app.config['SESSION_USE_SIGNER'] = True
app.config['SESSION_FILE_DIR'] = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'flask_session')

# 确保session目录存在
os.makedirs(app.config['SESSION_FILE_DIR'], exist_ok=True)

app.register_blueprint(bp)

# 配置日志
logging.basicConfig(stream=sys.stdout, level=logging.INFO)

@app.before_request
def before_first_request():
    """请求前初始化检查"""
    if not app_state.initialized:
        init_scheduler()

if __name__ == '__main__':
    app.logger.handlers.clear()
    app.logger.addHandler(logging.StreamHandler(sys.stdout))
    app.logger.setLevel(logging.INFO)
 
    init_scheduler()
    try:
        app.run(
            host='0.0.0.0',
            port=5000,
            debug=False,
            use_reloader=False
        )
    except Exception as e:
        app.logger.critical(f"应用启动失败: {str(e)}")
    finally:
        shutdown_scheduler()